package com.ds.app.database;

import com.ds.common.CommonConfig;
import com.ds.org.conf.OrgConfig;
import com.ds.org.conf.OrgConstants;
import com.ds.org.conf.Query.ColumnMapping;
import com.ds.server.eumus.ConfigCode;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.UUID;

public class DBBaseManager {
    private final ConfigCode configKey;
    protected OrgConfig config;
    protected boolean cacheEnabled;

    public DBBaseManager(ConfigCode configKey) {
        super();
        this.configKey = configKey;
        this.config = OrgConfig.getInstance();
    }


    protected String getString(ResultSet rs, Object column) {
        if (column != null) {
            try {
                return rs.getString(((ColumnMapping) column).getColumnAlias());
            } catch (SQLException ex) {
                return null;
            }
        }
        return null;
    }

    protected long getLong(ResultSet rs, Object column) {
        if (column != null) {
            try {
                return rs.getLong(((ColumnMapping) column).getColumnAlias());
            } catch (SQLException ex) {
                return 0l;
            }
        }
        return 0l;
    }

    protected Date getDate(ResultSet rs, Object column) {
        if (column != null && !column.toString().equals("")) {
            try {


                return rs.getDate(((ColumnMapping) column).getColumnAlias());
            } catch (SQLException ex) {
                return null;
            }
        }
        return null;
    }

    protected int getInt(ResultSet rs, Object column) {
        if (column != null) {
            try {
                return rs.getInt(((ColumnMapping) column).getColumnAlias());
            } catch (SQLException ex) {
                return 0;
            }
        }
        return 0;
    }


    /**
     * get the manager object used to get connections
     *
     * @return the manager used
     */
    protected // 2
    DbManager getManager() {
        return DbManager.getInstance(this.configKey);
    }

    /**
     * free connection
     *
     * @param c the connection to release
     */
    protected void freeConnection(Connection c) {
        getManager().releaseConnection(c); // back to pool
    }

    /**
     * get connection
     */
    protected Connection getConnection() throws SQLException {
        return getManager().getConnection();
    }

    public String generationUUID() {
        String _uuid = UUID.randomUUID().toString();
        return _uuid.replaceAll("-", "");
    }
}
